# !/usr/bin/env python3
# -*- coding: utf-8 -*-


import xml.etree.ElementTree as EleTree
from util.txt_engine import write_topo_or_stream_to_txt


def transforming_topo_feature(topo_xml, topo_txt):
    """
    将TSNLight的流特征的xml文件转换成OpenPlanner的拓扑文本文件
    :param topo_xml:
    :param topo_txt:
    :return:
    """
    # 从topo_xml中挑选出每一条链路的
    # link_id src_node_id dst_node_id speed st_queues macrotick 六个参数
    # 上述六个参数分别对应OpenPlanner的topo_txt中的
    # link_id src_node dst_node speed st_queues macrotick
    tree = EleTree.parse(topo_xml)
    entry_ele_set = tree.findall('entry')
    link_set = []
    for entry_ele in entry_ele_set:
        link_tmp = {}
        entry_ele_list = list(entry_ele)
        for ele in entry_ele_list:
            link_tmp.update({ele.tag: ele.text})
        link = {
            'link_id': link_tmp['link_id'],
            'src_node': link_tmp['src_node'],
            'dst_node': link_tmp['dst_node'],
            'speed': link_tmp['speed'],
            'st_queues': link_tmp['st_queues'],
            'macrotick': link_tmp['macrotick']
        }
        link_set.append(link)

    # 将这些参数写入stream_txt文件
    write_topo_or_stream_to_txt(topo_txt, link_set)
    return


def get_topo_set(topo_xml):
    """
    从topo_xml中获取link_id与[src_node, dst_node, src_port, dst_port]的对应关系
    """
    topo_set = []
    tree = EleTree.parse(topo_xml)
    link_ele_set = tree.findall('entry')
    for link_ele in link_ele_set:
        link_id = link_ele.findtext('link_id')
        src_node_id = link_ele.findtext('src_node')
        dst_node_id = link_ele.findtext('dst_node')
        src_port_id = link_ele.findtext('src_port')
        dst_port_id = link_ele.findtext('dst_port')
        topo_set.append({
            'link_id': int(link_id),
            'src_node_id': int(src_node_id),
            'dst_node_id': int(dst_node_id),
            'src_port_id': int(src_port_id),
            'dst_port_id': int(dst_port_id)
        })
    return topo_set


def get_time_slot_len(topo_xml):
    """
    从topo_xml中获取时间槽长度，时间槽长度值都一样，取第一个就行
    """
    tree = EleTree.parse(topo_xml)
    link_ele_set = tree.findall('entry')
    time_slot_len = link_ele_set[0].findtext('macrotick')
    time_slot_len = int(time_slot_len)

    return time_slot_len


def add_src_node_port_to_dst_set(dst_set, topo_set):
    for item in dst_set:
        link_id = item['link_id']
        for link in topo_set:
            if link_id == link['link_id']:
                node_id = link['src_node_id']
                port_id = link['src_port_id']
                item.update({'src_node_id': node_id, 'src_port_id': port_id})
                break
    return


